package com.appkudos.view;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.appkudos.controller.GroupController;
import com.appkudos.controller.RecController;
import com.appkudos.controller.UserController;
import com.appkudos.model.App;
import com.appkudos.model.Group;
import com.appkudos.model.Recommendation;
import com.appkudos.model.User;

public class UserProfileActivity extends Activity implements Runnable{
	private Activity PARENTACTIVITY;
	TextView userName;
	TextView addRecButton;
	TextView recommendation;
	ListView recList;
	ListView recentlyAddedList;
	ListView allRecList;
	ArrayList<Recommendation> recentRecs;
	ArrayList<App> recentApps;
	ArrayList<Recommendation> allRecs;
	User user;
	UserController uc;
	User friend;
	User userToDisplay;
	Button recBtn;
	
	// view review activity widgets
	Bundle extras;
	TextView recommender;
	TextView datesent;
	TextView recText;
	TextView appName;
	String app_name;
	RecController rc =  new RecController();
	Group group;	
	App app;
	
	String recid;
	String sender;
	String receiver;
	String msg;
	String isGroup;
	String isSent;
	String appid;

	String display_option;
	ProgressDialog pd;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);        
        setContentView(R.layout.view_user_profile);
	      /*set custom title
	      requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
	      getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);
	      
	      TextView tv = (TextView) getWindow().findViewById(R.id.titlebar_text);
	      tv.setText("User's Profile");
	    */    
	    PARENTACTIVITY = this;
	        
	    // get user info
	    Intent launchIntent = getIntent();
	    Bundle extras = launchIntent.getExtras();
	    uc = new UserController();
	    user = uc.getCurrentUser(extras);
	    // get friend info if exists
	    friend = uc.getFriend(extras);
//	    rec = uc.getRec(extras);
        display_option = extras.getString(PARENTACTIVITY.getString(R.string.display_opt));
        
        recid = extras.getString("recid");
    	sender = extras.getString("sender");
    	receiver = extras.getString("receiver");
    	msg = extras.getString("msg");
    	isGroup = extras.getString("isGroup");
    	isSent = extras.getString("isSent");
    	appid =  extras.getString("appid");

        if(display_option== null){
            initWidgets();
        }else if(display_option.equals(this.getString(R.string.view_rec))){ // display select app
	     	   displayViewRec(sender,receiver,msg,appid,Boolean.parseBoolean(isGroup),isSent);	    
	    }else if(display_option.equals("display_all")){
	    	displayAllRecs();
	    }
    }

    /***
     * Initialize components for user profile page
     */
    public void initWidgets() { 	
    	userName = (TextView) findViewById(R.id.vu_username);
    	if(friend == null){ // display user info
    		userName.setText(user.getUsername());
    	}else if(friend.getUsername().compareTo(user.getUsername())==0){
    		userName.setText(user.getUsername());
    	}else{// display friend info
    		
    	}
    	
    	addRecButton = (TextView) findViewById(R.id.vu_rec_plus_button);
    	
    	// display friend info
    	if(friend != null && friend.getUsername().compareTo(user.getUsername())!=0){
    		userName.setText(friend.getUsername());
    		userName.setCompoundDrawablesWithIntrinsicBounds(R.drawable.usericon3, 0, 0, 0);
		      
    		addRecButton.setVisibility(View.GONE);
    		
    		userToDisplay = friend;
    	       
    	}else{ // If the current person to be displayed is the user
    		if(friend != null && friend.getUsername().compareTo(user.getUsername())==0){
    			friend = null;
    		}
    		userToDisplay = user;
    		userName.setText(user.getUsername());
    		userName.setCompoundDrawablesWithIntrinsicBounds(R.drawable.usericon4, 0, 0, 0);
		    
    		TextView recText = (TextView) findViewById(R.id.vu_recommendations_text);
    		// Show all recs when Recommendations is clicked
    		recText.setOnClickListener(new OnClickListener(){
    			@Override
                public void onClick(View v) {     
                      Intent intent = new Intent(PARENTACTIVITY, AppKudos.class);
                      intent = uc.passCurrentUser(intent, user);
                      if(friend != null){
                      	intent = uc.passFriend(intent, friend);	
                      }
                      intent.putExtra("tab", PARENTACTIVITY.getString(R.string.tab_user_profile));
                      intent.putExtra("display_opt", "display_all");
              		  startActivity(intent);
    			}
    		});
    		
    		// Show more details on individual recommendation page when selected
            addRecButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {     
                      Intent intent = new Intent(PARENTACTIVITY, AppKudos.class);
                      intent = uc.passCurrentUser(intent, user);
                      intent.putExtra("tab", PARENTACTIVITY.getString(R.string.tab_user_app));
                      intent.putExtra("display_opt", "select_rec");
              		  startActivity(intent);
                }
              }); 
            
            userToDisplay = user;
    	}

    	recommendation = (TextView) findViewById(R.id.vu_recommendation_textview);
    	
    	// get list view from layout
        recList=(ListView)findViewById(R.id.recent_rec_list);
        
        pd = ProgressDialog.show(this, "", "Loading. Please wait...", true);
        
        Thread thread = new Thread(this);
        thread.start();
        
    }
    
    /**
     * Populates recommendations and recently added apps after fetching from DB.
     */
    public void initRemainingWidgets() {
        
        // Show the 3 most recent recs for this user, 2-line layout
        if(recentRecs.size() > 3){
        	recList.setAdapter(new RecArrayAdapter(this, R.layout.two_line_list_item, recentRecs.subList(0, 3)));
        }else if(recentRecs.size() > 0){
        	recList.setAdapter(new RecArrayAdapter(this, R.layout.two_line_list_item, recentRecs));
        }
    	recList.setOnItemClickListener(new OnItemClickListener() {
    		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		        	
    			// When clicked, show a toast with the TextView text
	        	Recommendation item = (Recommendation) recentRecs.get(position);
	               
//	        	displayViewRec(item.getSender(), item.getReceiver(), item.getMessage(), item.getAppid(), item.isGroupRecipient(), item.getDateSent());
            	Intent intent = new Intent(PARENTACTIVITY, AppKudos.class);
                intent = uc.passCurrentUser(intent, user);
                if(friend != null){
                	intent = uc.passFriend(intent, friend);	
                }
                intent.putExtra("display_opt", "view_rec");
                intent = uc.passRec(intent,item);

                intent.putExtra("tab", PARENTACTIVITY.getString(R.string.tab_user_profile));               
        		startActivity(intent);        		
        		
//        	    Intent intent = new Intent(PARENTACTIVITY, ViewReviewActivity.class);
//        	    intent = uc.passCurrentUser(intent, user);
//        	    intent.putExtra("app_id", item.getAppid());
//        	    intent.putExtra("rec_sender", item.getSender());
//        	    intent.putExtra("rec_receiver", item.getReceiver());
//        	    intent.putExtra("rec_message", item.getMessage());
//        	   
//        	    startActivity(intent);
    		}
	    });
        
        TextView recentAppsTitle = (TextView) findViewById(R.id.vu_recently_added_text);
		recentAppsTitle.setOnClickListener(new OnClickListener(){
			@Override
            public void onClick(View v) {     
                  Intent intent = new Intent(PARENTACTIVITY, AppKudos.class);
                  intent = uc.passCurrentUser(intent, user);
                  if(friend != null){
                  	intent = uc.passFriend(intent, friend);	
                  }
                  intent.putExtra("tab", PARENTACTIVITY.getString(R.string.tab_user_app));
          		  startActivity(intent);
			}
		});
        // Add recently added apps
        recentlyAddedList=(ListView)findViewById(R.id.recent_app_list);
        recentApps = (ArrayList<App>) uc.getRecentAppsForUser(userToDisplay.getUsername());
        
        String app_names[] = new String[recentApps.size()];
        
        for(int i = 0; i < recentApps.size(); i++){
        	app_names[i] = recentApps.get(i).getAppName();
        }
        
        if(recentApps.size()>0){
        	// Show the most recent apps added by this user in the past 30 days
        	recentlyAddedList.setAdapter(new ArrayAdapter<String>(this, R.layout.small_list_item, app_names));
        }
        
        recentlyAddedList.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {     
            	App item = (App) recentApps.get(position);  
            	Intent intent = new Intent(PARENTACTIVITY, AppKudos.class);
                  intent = uc.passCurrentUser(intent, user);
                  if(friend!=null){
                	  intent = uc.passFriend(intent, friend);
                  }
                  intent.putExtra("tab", PARENTACTIVITY.getString(R.string.tab_user_app));
                  intent.putExtra("display_opt", "view_app");
                  intent = uc.passApp(intent, item);
          		  startActivity(intent);
            }
          }); 
        
     
    }
    
    /***
     * Shows the View for an individual Recommendation specified by parameters from previous screen
     * @param rec_sender
     * @param rec_receiver
     * @param rec_message
     * @param app_id
     * @param isGroupRecipient
     * @param dateSent
     */
    private void displayViewRec(String rec_sender, String rec_receiver, String rec_message, String app_id, boolean isGroupRecipient, String dateSent){
    	setContentView(R.layout.view_review);
    	
    	String app_name = uc.getAppForUser(app_id).getAppName();
    	GroupController gc = new GroupController();
    	
    	if(isGroupRecipient){
			rec_receiver = gc.getGroupById(rec_receiver).getGroupName();
		}
    	
    	
		DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
		Date d = new Date();
		try {
			d = df.parse(dateSent.substring(0, 10));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String date = df.format(d);
    	
    	recommender = (TextView) findViewById(R.id.vr_recommendation);
    	datesent = (TextView) findViewById(R.id.vr_datesent);
    	recText = (TextView) findViewById(R.id.vr_comment_text);
    	appName = (TextView) findViewById(R.id.vr_app_name);
    	    	
    	
		recommender.setText(rec_sender + " recommended to " + rec_receiver);
		datesent.setText("Date: " + date);
		recText.setText("Message: " + "\"" + rec_message + "\"" );
		appName.setText(app_name);
		
		final String appid = app_id;
		
        appName.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {     
            	App item = uc.getAppForUser(appid);
            	Intent intent = new Intent(PARENTACTIVITY, AppKudos.class);
                  intent = uc.passCurrentUser(intent, user);
                  if(friend!=null){
                	  intent = uc.passFriend(intent, friend);
                  }
                  intent.putExtra("tab", PARENTACTIVITY.getString(R.string.tab_user_app));
                  intent.putExtra("display_opt", "view_app");
                  intent = uc.passApp(intent, item);
          		  startActivity(intent);
            }
          }); 
    }

    /***
     * Shows the View for viewing all Recommendations for this user
     */
    private void displayAllRecs(){
    	setContentView(R.layout.view_all_recs);
    	TextView title = (TextView) findViewById(R.id.all_recommendations_text);
    	TextView allAddRecButton = (TextView) findViewById(R.id.all_rec_plus_button);
    	// display friend info
    	if(friend != null && friend.getUsername().compareTo(user.getUsername())!=0){
    		title.setText(friend.getUsername() + "'s Recommendations");
    		title.setCompoundDrawablesWithIntrinsicBounds(R.drawable.usericon3, 0, 0, 0);
    		allAddRecButton.setVisibility(View.GONE);
    		userToDisplay = friend;
    	}else{ // If the current person to be displayed is the user
    		if(friend != null && friend.getUsername().compareTo(user.getUsername())==0){
    			friend = null;
    		}
    		userToDisplay = user;
    		title.setText("My Recommendations");
    		title.setCompoundDrawablesWithIntrinsicBounds(R.drawable.usericon4, 0, 0, 0);
		    
    		// Show more details on individual recommendation page when selected
            allAddRecButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {     
                      Intent intent = new Intent(PARENTACTIVITY, AppKudos.class);
                      intent = uc.passCurrentUser(intent, user);
                      intent.putExtra("tab", PARENTACTIVITY.getString(R.string.tab_user_app));
                      intent.putExtra("display_opt", "select_rec");
              		  startActivity(intent);
                }
              }); 
    	}
    	
    	// get list view from layout
        allRecList =(ListView)findViewById(R.id.all_rec_list);
        allRecs = (ArrayList<Recommendation>) uc.getRecsForUser(userToDisplay.getUsername());
       
        allRecList.setAdapter(new RecArrayAdapter(this, R.layout.two_line_list_item, allRecs));
        
        allRecList.setOnItemClickListener(new OnItemClickListener() {
    		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    			// When clicked, show a toast with the TextView text
	        	Recommendation item = (Recommendation) allRecs.get(position);

	        	Intent intent = new Intent(PARENTACTIVITY, AppKudos.class);
                intent = uc.passCurrentUser(intent, user);
                if(friend != null){
                	intent = uc.passFriend(intent, friend);	
                }
                intent.putExtra("display_opt", "view_rec");
                intent = uc.passRec(intent,item);

                intent.putExtra("tab", PARENTACTIVITY.getString(R.string.tab_user_profile));               
        		startActivity(intent);
    		}
	    });
        
    }
    
    /***
     * Fetches recommendations and recently added apps in the background
     * Called when the thread starts
     * Note: Cannot alter View elements in the background
     */
    public void run() {
    	recentRecs = (ArrayList<Recommendation>) uc.getRecentRecsForUser(userToDisplay.getUsername());
    	recentApps = (ArrayList<App>) uc.getRecentAppsForUser(userToDisplay.getUsername());
    	handler.sendEmptyMessage(0);
    }
    
    /***
     *  Gets called when the thread is finished running
     *  Closes progress dialog and updates View elements
     */
    private Handler handler = new Handler() {
    	@Override
        public void handleMessage(Message msg) {
    		if(pd != null && pd.isShowing()){
                pd.dismiss();
    		}
    	    initRemainingWidgets();
    	}
    };
}